import { message } from 'antd'
import axios from 'axios'
import { createHashHistory } from 'history'

const instance = axios.create({
  baseURL: 'http://localhost:8080/',
})

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = localStorage.getItem('token')
    return config
  },
  (error) => error
)

// 响应拦截
instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 401) {
      console.log(res.data)
      message.error(res.data.message)
      setTimeout(() => {
        createHashHistory().push('/login')
      }, 2000)
    }
    return res.data
  },
  (error) => error
)

export const request = {
  get: function (config) {
    return instance({
      ...config,
      method: 'GET',
      params: config.data,
    })
  },
  post: function (config) {
    return instance({
      ...config,
      method: 'POST',
    })
  },
  put: function (config) {
    return instance({
      ...config,
      method: 'PUT',
      params: config.data,
    })
  },
  delete: function (config) {
    return instance({
      ...config,
      method: 'DELETE',
      params: config.data,
    })
  },
}
